const http = require('http');

const fs = require('fs');

const url = require('url');

const path = require('path');
// 因为是样式  我们特意在路径上加前一个前缀
// style

// localhost:8899/style/home.css
// localhost:8899/style/list.css
// localhost:8899/style/detail.css

// 创建一个服务

const server = http.createServer(function(req,res){
    const {query,pathname} = url.parse(req.url,true);

    // localhost:8899
    // if(pathname === '/'){
    //     fs.readFile('./client/views/home.html','utf8',(err,data)=>{
    //         if(err){
    //             console.log(err);
    //         }else{
    //             res.end(data);
    //         }
    //     })
    // }
    // css 样式是以 style 开头的
    // 页面.html    以 views开头 

    // localhost:8899/style/home.css
    // localhost:8899/views/home.html

    // localhost:8899/views/home
    // localhost:8899/views/list
    // localhost:8899/views/detail
    if(/^\/views/.test(pathname)){
        const { base } = path.parse(pathname);
        console.log(base);
        fs.readFile(`./client/views/${base}.html`,'utf8',(err,data)=>{
            if(err){
                fs.readFile('./client/views/404.html','utf8',(err,data)=>{
                    res.end(data);
                })
            }else{
                res.end(data);
            }
    })

}
    // localhost:8899/style/home.css
    if(/^\/style/.test(pathname)){
        // console.log(pathname);// 
        // style/home.css

        // 我就要到client文件夹css下面去找这个文件
        const {base} = path.parse(pathname);
        // console.log( path.parse(pathname));
        // base 就是文件名
        // base 就是home.css

        fs.readFile(`./client/css/${base}`,'utf-8',(err,data)=>{
            if(err){
                console.log(err);
            }else{
                res.end(data);
            }
        })
    }
})


// 启动 服务

server.listen(8899,()=>{
    console.log('服务开启成功');
})